<?php

namespace App\Console\Commands;

use App\Advertiser;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class SyncAdvertiser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:advertiser';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步广告主';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Log::info("定时任务同步广告主开始");
        $cursor = '';
        while (true) {
            Log::info("获取广告账户游标【". $cursor."】");
            $responseData = $this->getata($cursor);
            if (isset($responseData['data']['list']) && count($responseData['data']['list']) > 0) {
                $listData = $responseData['data']['list'];

                foreach ($listData as $advertiser) {
                    Advertiser::query()->updateOrCreate([
                        'account_id' => $advertiser['account_id'],
                    ], [
                        'system_status' => $advertiser['system_status'],
                        'corporation_name' => $advertiser['corporation_name'],
                        'corporation_licence' => $advertiser['corporation_licence'] ?? '',
                        'corporate_brand_name' => $advertiser['corporate_brand_name'] ?? '',
                        'system_industry_id' => $advertiser['system_industry_id'] ?? 0,
                        'customized_industry' => $advertiser['customized_industry'] ?? '',
                        'agency_account_id' => $advertiser['agency_account_id'] ?? 0
                    ]);
                }
            }
            if (!isset($responseData['data']['cursor_page_info']['has_more']) || !$responseData['data']['cursor_page_info']['has_more']) {
                break;
            }
            if (isset($responseData['data']['cursor_page_info']['cursor']) && $responseData['data']['cursor_page_info']['cursor']) {
                $cursor = $responseData['data']['cursor_page_info']['cursor'];
            } else {
                break;
            }
        }

    }

    private function getata(string $cursor = '')
    {
        $interface = 'advertiser/get';
        $url = 'https://api.e.qq.com/v3.0/' . $interface;

        $common_parameters = array (
            'access_token' => \config('app.tencent_access_token'),
            'timestamp' => time(),
            'nonce' => md5(uniqid('', true))
        );

        $parameters = array (
            'agency_id' => \config('app.tencent_agency_id'),
//            'filtering' => [],
            'fields' => ['system_status', 'corporation_name', 'corporation_licence', 'corporate_brand_name', 'system_industry_id', 'customized_industry', 'agency_account_id'],
            'pagination_mode' => 'PAGINATION_MODE_CURSOR',
            'cursor' => $cursor,
            'page_size' => 100,
        );

        $parameters = array_merge($common_parameters, $parameters);

        foreach ($parameters as $key => $value) {
            if (!is_string($value)) {
                $parameters[$key] = json_encode($value);
            }

        }

        $request_url = $url . '?' . http_build_query($parameters);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $request_url);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($curl);
        if (curl_error($curl)) {
            $error_msg = curl_error($curl);
            $error_no = curl_errno($curl);
            curl_close($curl);

            Log::error("获取广告账户返回错误: ", [
                'error_msg' => $error_msg,
                'error_no' => $error_no
            ]);
            return [];
//            throw new \Exception($error_msg, $error_no);
        }
        curl_close($curl);
        $responseData = json_decode($response, true);
        if (!isset($responseData['code']) || $responseData['code'] != 0) {
            Log::debug("获取广告账户返回错误: ", [
                'data' => $responseData,
                'params' => $parameters
            ]);

            return [];
        }
        return $responseData;
    }
}
